<template>
  <div class="manual-import-page">
    <!-- 移除标题区域 -->

    <!-- 直接在页面中显示手动导入功能，而不是通过对话框 -->
    <div class="manual-import-content">
      <el-collapse v-model="activeNames" style="margin-bottom: 15px;">
        <el-collapse-item name="1">
          <template #title>
            <el-icon style="color: #409eff;">
              <InfoFilled />
            </el-icon>
            <span style="margin-left: 8px; color: #409eff; font-weight: 500;">导入格式说明（点击展开）</span>
          </template>
          <div>
            <p><strong>请按照以下格式输入题目内容：</strong></p>
            <p><strong>格式示例：</strong></p>
            <pre style="background-color: #f5f7fa; padding: 10px; border-radius: 4px; overflow-x: auto;">
    【例 1】题目内容...
    A. 选项A
    B. 选项B
    C. 选项C
    D. 选项D
    正确答案：A
    解析：解析内容

    【例 2】题目内容...
    A. 选项A
    B. 选项B
    C. 选项C
    D. 选项D
    正确答案：B
    解析：解析内容</pre>
            <p><strong>注意事项：</strong></p>
            <ul>
              <li>使用【例 X】作为题目标识，X为题目序号</li>
              <li>题目内容与选项之间不要有空行</li>
              <li>选项格式为大写字母加点，如A. B. C. D.</li>
              <li>正确答案格式为"正确答案：X"，X为选项字母</li>
              <li>解析为可选内容，格式为"解析：解析内容"</li>
              <li>支持批量导入多个题目</li>
              <li>系统会自动移除题目内容中的多余空格</li>
            </ul>
          </div>
        </el-collapse-item>
      </el-collapse>

      <el-form>
        <!-- 模块选择 -->
        <el-form-item label="模块选择：">
          <el-select v-model="importModuleType" placeholder="请选择模块" @change="handleModuleChange" style="width: 200px;">
            <el-option label="时政" value="politics" />
            <el-option label="常识" value="commonSense" />
            <el-option label="言语理解" value="language" />
            <el-option label="判断" value="judgment" />
            <el-option label="数量" value="quantitative" />
            <el-option label="资料分析" value="dataAnalysis" />
          </el-select>
        </el-form-item>

        <!-- 时政模块使用时间选择器 -->
        <el-form-item label="时间筛选：" v-if="importModuleType === 'politics'">
          <el-date-picker v-model="importCategory" type="date" placeholder="请选择时间" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" style="width: 200px;" />
        </el-form-item>

        <!-- 其他模块使用大分类和小分类输入框 -->
        <template v-else-if="importModuleType">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="大的分类：">
                <el-select v-model="importCategory" placeholder="请选择大分类" clearable @change="handleCategoryChange">
                  <el-option v-for="category in categoryOptions" :key="category.value" :label="category.label"
                    :value="category.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="小的分类：">
                <el-select v-model="importSubCategory" placeholder="请选择小分类" clearable :disabled="!importCategory">
                  <el-option v-for="subCategory in subCategoryOptions" :key="subCategory.value"
                    :label="subCategory.label" :value="subCategory.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!-- 操作按钮放在上方 -->
        <div class="form-actions-top">
          <el-button @click="resetImport">重置</el-button>
          <el-button type="warning" @click="validateFormat">格式验证</el-button>
          <el-button type="primary" @click="executeImport" :disabled="!isFormatValid">批量导入</el-button>
          <!-- 将验证结果提示移到按钮旁边 -->
          <div v-if="isFormatValid" class="validation-result valid" style="display: inline-block; margin-left: 15px;">
            <el-icon color="#67c23a">
              <SuccessFilled />
            </el-icon>
            格式验证通过，共识别到 {{ parsedQuestions.length }} 道题目
          </div>

          <div v-if="importContent && !isFormatValid" class="validation-result invalid"
            style="display: inline-block; margin-left: 15px;">
            <el-icon color="#f56c6c">
              <CircleCloseFilled />
            </el-icon>
            格式验证未通过，请检查输入内容
          </div>
        </div>

        <!-- 左右布局：左边输入框，右边预览 -->
        <div class="input-preview-layout">
          <!-- 左边：输入框 -->
          <div class="input-section">
            <!-- "题目内容"标签单独占一行，输入框在下方 -->
            <div class="content-label-row">
              <label class="content-label">题目内容：</label>
            </div>
            <div class="content-input-container">
              <el-input v-model="importContent" type="textarea" :autosize="{ minRows: 15 }"
                placeholder="请在此粘贴题目内容，支持批量导入多个题目" @input="onContentInput" class="content-textarea" />
            </div>
          </div>

          <!-- 右边：预览区域 -->
          <div class="preview-section">
            <!-- "题目预览"标题单独占一行 -->
            <div class="preview-header">
              <h3 class="preview-title">题目预览</h3>
            </div>
            <div class="question-preview">
              <div v-if="parsedQuestions.length === 0" class="no-preview">
                <el-empty description="暂无预览内容" />
              </div>
              <div v-else class="preview-content">
                <div class="question-item" v-for="(question, index) in parsedQuestions" :key="index">
                  <div class="question-header">
                    <span class="question-number">题目 {{ index + 1 }}</span>
                  </div>
                  <div class="question-content"><span v-html="question.content"></span></div>
                  <div class="question-options">
                    <div class="option-item" v-for="(option, key) in question.options" :key="key">
                      {{ key }}. {{ option }}
                    </div>
                  </div>
                  <div class="question-answer">正确答案：{{ question.answer }}</div>
                  <div v-if="question.explanation" class="question-explanation">解析：{{ question.explanation }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { InfoFilled, SuccessFilled, CircleCloseFilled } from '@element-plus/icons-vue';
import * as politicsApi from '@/api/politics';
import * as commonSenseApi from '@/api/commonsense';
import * as languageApi from '@/api/language';
import * as judgmentApi from '@/api/judgment';
import * as quantityApi from '@/api/quantity';
import * as dataAnalysisApi from '@/api/dataAnalysis';

// 响应式数据
const activeNames = ref([]); // 默认不展开格式说明
const importContent = ref('');
const importModuleType = ref('politics'); // 默认模块类型为时政
const importCategory = ref(''); // 大分类字段
const importSubCategory = ref(''); // 小分类字段
const isFormatValid = ref(false);
const parsedQuestions = ref<any[]>([]);
let contentInputTimer: any = null;

// 模块API映射
const moduleApiMap: Record<string, any> = {
  politics: politicsApi,
  commonSense: commonSenseApi,
  language: languageApi,
  judgment: judgmentApi,
  quantitative: quantityApi,
  dataAnalysis: dataAnalysisApi
};

// 分类选项
const categoryOptions = computed(() => {
  const categories: Record<string, Array<{ label: string; value: string }>> = {
    // 常识模块分类
    commonSense: [
      { label: '政治', value: 'Politics' },
      { label: '经济', value: 'Economics' },
      { label: '文史', value: 'HistoryLiterature' },
      { label: '科学与生活', value: 'ScienceLife' },
      { label: '地理', value: 'Geography' },
      { label: '法律', value: 'Law' },
      { label: '管理与公文', value: 'ManagementDocuments' }
    ],
    // 言语模块分类
    language: [
      { label: '片段阅读', value: 'SegRead' },
      { label: '语句表达', value: 'SenExp' },
      { label: '逻辑填空', value: 'LogFill' }
    ],
    // 数量模块分类
    quantitative: [
      { label: '倍数特性', value: 'MulCha' },
      { label: '方程问题', value: 'EquPro' },
      { label: '等差数列和等比数列', value: 'AriGeoSeq' },
      { label: '周期问题', value: 'PerPro' },
      { label: '工程问题', value: 'EngPro' },
      { label: '几何问题', value: 'GeoPro' },
      { label: '容斥原理问题', value: 'IncExcPro' },
      { label: '最值问题', value: 'ExtValPro' },
      { label: '年龄问题', value: 'AgePro' },
      { label: '溶液问题', value: 'SolPro' },
      { label: '植树与方程问题', value: 'PlanEquPro' },
      { label: '经济利润问题', value: 'EcoPro' },
      { label: '行程问题', value: 'TraPro' },
      { label: '排列组合问题', value: 'ComPermPro' },
      { label: '数量易拿分小题型', value: 'EasyNumPro' }
    ],
    // 判断模块分类
    judgment: [
      { label: '定义推理', value: 'DefRea' },
      { label: '类比推理', value: 'AnaRea' },
      { label: '逻辑推理', value: 'LogRea' },
      { label: '图形推理', value: 'GraRea' }
    ],
    // 资料模块分类
    dataAnalysis: [
      { label: '八大常用速算技巧', value: 'FastCal' },
      { label: '基期量', value: 'BaseVal' },
      { label: '现期量', value: 'CurrVal' },
      { label: '增长率', value: 'GrowthRt' },
      { label: '增长量', value: 'GrowthAmt' },
      { label: '间隔增长率', value: 'IntvGrowth' },
      { label: '乘积增长率', value: 'ProdGrowth' },
      { label: '年均增长率', value: 'AnnGrowth' },
      { label: '混合增长率', value: 'MixGrowth' },
      { label: '比重', value: 'Proportion' },
      { label: '平均数', value: 'Average' },
      { label: '倍数', value: 'Multiple' },
      { label: 'A与非A思想', value: 'ANotA' },
      { label: '综合分析', value: 'CompAnaly' }
    ]
  };

  return categories[importModuleType.value] || [];
});

// 子分类选项
const subCategoryOptions = computed(() => {
  // 根据主分类返回相应的子分类选项
  const subCategories: Record<string, Array<{ label: string; value: string }>> = {
    // 常识模块子分类
    Politics: [
      { label: '时事政治', value: 'CurrentPolitics' },
      { label: '政策解读', value: 'PolicyInterpretation' },
      { label: '政治理论', value: 'PoliticalTheory' }
    ],
    Economics: [
      { label: '宏观经济', value: 'MacroEconomics' },
      { label: '微观经济', value: 'MicroEconomics' },
      { label: '经济政策', value: 'EconomicPolicy' }
    ],
    HistoryLiterature: [
      { label: '中国历史', value: 'ChineseHistory' },
      { label: '世界历史', value: 'WorldHistory' },
      { label: '文学常识', value: 'LiteraryKnowledge' }
    ],
    ScienceLife: [
      { label: '自然科学', value: 'NaturalScience' },
      { label: '生活常识', value: 'LifeCommonSense' },
      { label: '科技前沿', value: 'TechnologyFrontier' }
    ],
    Geography: [
      { label: '自然地理', value: 'PhysicalGeography' },
      { label: '人文地理', value: 'HumanGeography' },
      { label: '地理常识', value: 'GeographicalKnowledge' }
    ],
    Law: [
      { label: '宪法法律', value: 'ConstitutionalLaw' },
      { label: '行政法', value: 'AdministrativeLaw' },
      { label: '民法', value: 'CivilLaw' }
    ],
    ManagementDocuments: [
      { label: '管理学', value: 'Management' },
      { label: '公文写作', value: 'OfficialDocumentWriting' },
      { label: '行政管理', value: 'AdministrativeManagement' }
    ],
    // 言语模块子分类
    SegRead: [
      { label: '中心理解题', value: 'CentralComprehension' },
      { label: '细节判断题', value: 'DetailJudgment' }
    ],
    SenExp: [
      { label: '接语选择题', value: 'DiscourseSelection' },
      { label: '语句填空题', value: 'SentenceFilling' },
      { label: '语句排序题', value: 'SentenceOrdering' }
    ],
    LogFill: [
      { label: '词的辨析', value: 'WordAnalysis' },
      { label: '语境分析', value: 'ContextualAnalysis' }
    ],
    // 数量模块子分类
    MulCha: [
      { label: '奇偶性', value: 'Parity' },
      { label: '整除特性', value: 'Divisibility' },
      { label: '比例倍数', value: 'RatioMultiple' }
    ],
    EquPro: [
      { label: '一元一次方程', value: 'LinearEquation' },
      { label: '二元一次方程', value: 'BinaryLinearEquation' },
      { label: '不定方程', value: 'IndeterminateEquation' }
    ]
    // 其他模块的子分类可以继续添加...
  };

  return subCategories[importCategory.value] || [];
});

// 处理模块选择变化
const handleModuleChange = (moduleType: string) => {
  // 重置分类字段
  importCategory.value = '';
  importSubCategory.value = '';
};

// 处理大分类变化
const handleCategoryChange = (category: string) => {
  // 重置小分类字段
  importSubCategory.value = '';
};

// 输入内容变化时的处理
const onContentInput = () => {
  // 添加防抖，避免频繁验证
  if (contentInputTimer) {
    clearTimeout(contentInputTimer);
  }
  contentInputTimer = setTimeout(() => {
    if (importContent.value.trim()) {
      validateFormatSilently();
    }
  }, 500);
};

// 静默验证格式（不显示消息提示）
const validateFormatSilently = () => {
  try {
    const content = importContent.value.trim();
    if (!content) {
      isFormatValid.value = false;
      parsedQuestions.value = [];
      return;
    }

    // 按照示例格式解析内容
    const questions = parseQuestions(content);
    if (questions.length > 0) {
      parsedQuestions.value = questions;
      isFormatValid.value = true;
    } else {
      isFormatValid.value = false;
      parsedQuestions.value = [];
    }
  } catch (error) {
    isFormatValid.value = false;
    parsedQuestions.value = [];
  }
};

// 解析输入的题目内容
const parseQuestions = (content: string) => {
  const questions: any[] = [];
  // 按照示例格式解析
  // 使用【例 X】作为题目分隔符
  const questionBlocks = content.split(/【例\s*\d+】/).filter(block => block.trim());

  for (const block of questionBlocks) {
    const trimmedBlock = block.trim();
    if (!trimmedBlock) continue;

    // 直接提取题目内容（从开始到第一个选项之前的部分）
    let questionContent = '';
    // 查找第一个选项的位置 (A. B. C. D.)
    const firstOptionMatches = [...trimmedBlock.matchAll(/([A-D])\./g)];
    if (firstOptionMatches.length > 0) {
      const firstOptionIndex = firstOptionMatches[0].index || 0;
      questionContent = trimmedBlock.substring(0, firstOptionIndex).trim();
    } else {
      // 如果没有找到选项，使用整个块作为内容
      questionContent = trimmedBlock;
    }

    // 移除题目编号部分（如【例 1】）
    const contentWithoutNumber = questionContent.replace(/【例\s*\d+】/, '').trim();

    // 移除来源信息（括号内容）
    let finalContent = contentWithoutNumber.replace(/\([^)]*\)/, '').trim();

    // 保持原有的<p>标签结构，但确保格式正确
    // 如果内容中已经包含<p>标签，则保持原样
    if (finalContent.includes('<p>')) {
      // 确保<p>标签正确闭合
      if (!finalContent.startsWith('<p>')) {
        finalContent = '<p>' + finalContent;
      }
      if (!finalContent.endsWith('</p>')) {
        finalContent = finalContent + '</p>';
      }
      // 修复可能的标签问题
      finalContent = finalContent.replace(/<p>(\s*)<p>/g, '<p>').replace(/<\/p>(\s*)<\/p>/g, '</p>');
    } else {
      // 如果没有<p>标签，按照原来的逻辑处理
      finalContent = finalContent.replace(/\n/g, '<br>');
    }

    // 根据文本内容预处理规范，移除多余空白字符
    finalContent = finalContent.replace(/\s+/g, ' ');

    // 提取选项
    const options: Record<string, string> = {};
    const optionPattern = /([A-D])\.\s*([^\n]*?)(?=\n[A-D]\.|\s*[A-D]、|\s*正确答案：|$)/gs;
    const optionMatches = [...trimmedBlock.matchAll(optionPattern)];
    for (const match of optionMatches) {
      options[match[1]] = match[2].trim();
    }

    // 提取正确答案
    const answerMatch = trimmedBlock.match(/正确答案：\s*([A-D])/);
    const answer = answerMatch ? answerMatch[1] : '';

    // 提取解析（如果存在）
    // 修复正则表达式以正确提取解析内容
    const explanationMatch = trimmedBlock.match(/解析：\s*([\s\S]*?)(?=【例\s*\d+】|$)/);
    const explanation = explanationMatch ? explanationMatch[1].trim() : '';

    questions.push({
      content: finalContent,
      options,
      answer,
      explanation,
      source: '', // 不提取来源信息
      type: 'single_choice', // 默认为单选题
      difficulty: 'medium' // 默认难度
    });
  }

  return questions;
};

// 格式验证
const validateFormat = () => {
  try {
    const content = importContent.value.trim();
    if (!content) {
      ElMessage.warning('请输入题目内容');
      isFormatValid.value = false;
      return;
    }

    // 按照示例格式解析内容
    const questions = parseQuestions(content);
    if (questions.length > 0) {
      parsedQuestions.value = questions;
      isFormatValid.value = true;
      ElMessage.success(`格式正确，共识别到 ${questions.length} 道题目`);
    } else {
      isFormatValid.value = false;
      ElMessage.error('未识别到有效题目格式');
    }
  } catch (error) {
    isFormatValid.value = false;
    ElMessage.error('格式验证失败: ' + (error as Error).message);
  }
};

// 执行批量导入
const executeImport = async () => {
  if (!isFormatValid.value || parsedQuestions.value.length === 0) {
    ElMessage.warning('请先验证格式或没有可导入的题目');
    return;
  }

  // 获取对应的API模块
  const targetApiModule = moduleApiMap[importModuleType.value] || politicsApi;

  try {
    let successCount = 0;
    for (const question of parsedQuestions.value) {
      // 获取分类和子分类的中文标签
      const categoryLabel = getCategoryLabel(importCategory.value);
      const subCategoryLabel = getSubCategoryLabel(importCategory.value, importSubCategory.value);
      
      // 准备题目数据
      const questionData = {
        content: question.content,
        questionType: 'single_choice',
        difficulty: question.difficulty,
        options: JSON.stringify(question.options),
        correctAnswer: question.answer,
        explanation: question.explanation || '',
        category: categoryLabel || importCategory.value || '', // 使用中文标签
        subCategory: subCategoryLabel || importSubCategory.value || '' // 使用中文标签
      };

      try {
        const response = await targetApiModule.addQuestion(questionData);
        if (response.code === 200) {
          successCount++;
        }
      } catch (error) {
        console.error('导入单个题目失败:', error);
      }
    }

    ElMessage.success(`成功导入 ${successCount} 道题目`);
    resetImport();
  } catch (error) {
    ElMessage.error('批量导入失败: ' + (error as Error).message);
  }
};

// 获取分类的中文标签
const getCategoryLabel = (categoryValue: string) => {
  const categories = categoryOptions.value;
  const category = categories.find((cat: any) => cat.value === categoryValue);
  return category ? category.label : categoryValue;
};

// 获取子分类的中文标签
const getSubCategoryLabel = (categoryValue: string, subCategoryValue: string) => {
  const subCategories = subCategoryOptions.value;
  const subCategory = subCategories.find((subCat: any) => subCat.value === subCategoryValue);
  return subCategory ? subCategory.label : subCategoryValue;
};

// 重置导入
const resetImport = () => {
  importContent.value = '';
  importModuleType.value = 'politics'; // 重置为默认模块
  importCategory.value = ''; // 重置大分类
  importSubCategory.value = ''; // 重置小分类
  isFormatValid.value = false;
  parsedQuestions.value = [];
  if (contentInputTimer) {
    clearTimeout(contentInputTimer);
  }
};

// 组件挂载时的处理
onMounted(() => {
  // 可以在这里添加初始化逻辑
});
</script>

<style scoped>
.manual-import-page {
  /* 移除padding，使页面铺满整个窗口 */
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.manual-import-content {
  /* 移除padding，使内容铺满剩余空间 */
  flex: 1;
  overflow: auto;
  padding: 20px;
}

/* 顶部操作按钮 */
.form-actions-top {
  margin: 15px 0;
  text-align: center;
}

.form-actions-top .el-button {
  margin: 0 10px;
}

.input-preview-layout {
  display: flex;
  gap: 20px;
  height: calc(100% - 200px);
  /* 调整高度计算，考虑按钮区域 */
}

.input-section {
  flex: 1;
  min-width: 300px;
  display: flex;
  flex-direction: column;
}

/* 左侧"题目内容"标签单独占一行 */
.content-label-row {
  margin-bottom: 8px;
}

.content-label {
  font-size: 14px;
  color: #606266;
  font-weight: normal;
}

/* 输入框容器 */
.content-input-container {
  flex: 1;
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
}

.content-textarea {
  flex: 1;
}

.preview-section {
  flex: 1;
  min-width: 300px;
  display: flex;
  flex-direction: column;
}

/* 右侧"题目预览"标题单独占一行 */
.preview-header {
  margin-bottom: 8px;
}

.preview-title {
  font-size: 14px;
  color: #606266;
  margin: 0;
  font-weight: normal;
}

.question-preview {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  height: 100%;
  /* 确保预览区域与输入框高度一致 */
}

.question-preview .preview-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.no-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.question-item {
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 15px;
  background-color: #fafafa;

  &:last-child {
    margin-bottom: 0;
  }

  .question-header {
    margin-bottom: 10px;

    .question-number {
      font-weight: bold;
      color: #409eff;
    }
  }

  .question-content {
    font-weight: normal;
    /* 移除粗体，使其与输入框文字大小一致 */
    margin-bottom: 10px;
    color: #333;
    font-size: 14px;
    /* 明确设置字体大小与输入框一致 */
  }

  .question-options {
    margin: 10px 0;

    .option-item {
      margin-left: 15px;
      margin-bottom: 5px;
      color: #666;
      font-size: 14px;
      /* 设置选项字体大小与输入框一致 */
    }
  }

  .question-answer {
    color: #67c23a;
    font-weight: normal;
    /* 调整为正常字重 */
    margin-top: 10px;
    font-size: 14px;
    /* 设置字体大小与输入框一致 */
  }

  .question-explanation {
    color: #909399;
    margin-top: 8px;
    font-size: 14px;
  }
}

/* 验证结果提示样式 */
.validation-result {
  margin: 10px 0 15px 0;
  /* 调整外边距，使其更靠近输入框 */
  padding: 10px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;

  &.valid {
    background-color: #f0f9eb;
    border: 1px solid #e1f3d8;
    color: #67c23a;
  }

  &.invalid {
    background-color: #fef0f0;
    border: 1px solid #fbc4c4;
    color: #f56c6c;
  }
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .input-preview-layout {
    flex-direction: column;
    height: auto;
  }

  .input-section,
  .preview-section {
    min-width: auto;
  }

  .question-preview {
    height: 300px;
  }
}
</style>